//
//  ColorTool.m
//  TraderMobileKYi
//
//  Created by shijiezhao on 10/6/17.
//  Copyright © 2017年 com.yeezsoft.init. All rights reserved.
//

#import "SJColorConvertTool.h"

@implementation SJColorConvertTool



/**
 字符串转化成颜色

 @param colorString 颜色字符串
 @return 颜色
 */
+(UIColor *) colorWithHexString: (NSString *)colorString
{
    UIColor *color = [self colorWithHexString:colorString alpha:1.0f];
    return color;
}


/**
 字符串转化成颜色，带透明度

 @param color 颜色字符串
 @param alpha 透明度
 @return 颜色
 */
+(UIColor *) colorWithHexString: (NSString *)color alpha:(float)alpha
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:alpha];
}

/**
 RGB颜色

 @param r r
 @param g r
 @param b r
 @return 颜色
 */
+ (UIColor *)colorRedWithR:(NSInteger)r G:(NSInteger)g B:(NSInteger)b
{
    UIColor *color = [self colorRedWithR:r G:g B:b alpha:1.0f];
    return color;
}


/**
 RGB颜色
 
 @param r r
 @param g r
 @param b r
 @param alpha 透明度
 @return 颜色
 */
+ (UIColor *)colorRedWithR:(NSInteger)r G:(NSInteger)g B:(NSInteger)b alpha:(float)alpha
{
    UIColor *color = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:alpha] ;
    return color;
}




/// 根据颜色生成UIImage
/// @param color 颜色
+ (UIImage*)imageWithColor:(UIColor*)color
{

    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开始画图的上下文
    UIGraphicsBeginImageContext(rect.size);

    // 设置背景颜色
    [color set];
    // 设置填充区域
    UIRectFill(CGRectMake(0, 0, rect.size.width, rect.size.height));

    // 返回UIImage
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    return image;
}


@end
